package com.example.a053testthreaddemo;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    Button btnError, btnBasicThread, btnRunnable;
    TextView txtInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtInfo = (TextView) findViewById(R.id.txtInfo);
        btnError = (Button) findViewById(R.id.btnError);
        btnBasicThread = (Button) findViewById(R.id.btnBasic);
        btnRunnable = (Button) findViewById(R.id.btnRunnable);

        btnError.setOnClickListener(new mClick());
        btnBasicThread.setOnClickListener(new mClick());
        btnRunnable.setOnClickListener(new mClick());
    }

    class mClick implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            if (view == btnError) {
                // 匿名类接口方式，启动一个新的子线程，但由于Android不允许在子线程中修改UI组件
                // 所以，程序会直接崩溃，在logcat中可以查看到信息：
                // ThreadException: Only the original thread that created a view hierarchy can touch its views.
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // 这里会导致崩溃，因为在子线程修改UI
                        txtInfo.setText("崩溃ing......");
                    }
                }).start(); // 启动线程
            } // btnError 点击事件
            else if (view == btnBasicThread) {
                Intent intent = new Intent(MainActivity.this, basicThread.class);
                startActivity(intent);
            } // btnBasicThread 点击事件
            else if (view == btnRunnable) {
                Intent intent = new Intent(MainActivity.this, calculatePrime.class);
                startActivity(intent);
            } // btnRunnable 点击事件
        }
    }
}